package com.lagou.wwyan.rpc.handler;

import com.lagou.wwyan.rpc.bean.RpcRequest;
import com.lagou.wwyan.rpc.bean.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.SynchronousQueue;

public class RPCClientHandler extends ChannelInboundHandlerAdapter {

    private ChannelHandlerContext context;
    private Map<String, SynchronousQueue<RpcResponse>> rpcQueueMap = new ConcurrentHashMap<>();




    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        this.context = ctx;

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 读取数据
        RpcResponse response = (RpcResponse) msg;
        System.out.println("客户端接收到响应："+response.getRequestId());

        SynchronousQueue<RpcResponse> queue = rpcQueueMap.get(response.getRequestId());
        if (queue == null){
            System.out.println("请求id不存在");
            return;
        }
        queue.offer(response);

    }

    public RpcResponse sendRequest(RpcRequest rpcRequest) throws Exception {
        System.out.println("客户端发送请求："+rpcRequest.getRequestId());

        SynchronousQueue<RpcResponse> queue = new SynchronousQueue<>();
        rpcQueueMap.put(rpcRequest.getRequestId(), queue);
        context.writeAndFlush(rpcRequest);


        RpcResponse response = queue.take();

        rpcQueueMap.remove(rpcRequest.getRequestId());

        return response;
    }




}
